package com.ruoyi.smart.config;

import com.ruoyi.smart.mqtt.MessageHandler;
import com.ruoyi.smart.mqtt.MqttClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import java.util.List;

/**
 * 自动注册所有消息处理器到MQTT客户端
 */
@Slf4j
@Configuration
public class MqttHandlerConfiguration {

    @Autowired
    private MqttClient mqttClient;

    @Autowired(required = false) //  required = false 确保没有处理器时也能启动
    private List<MessageHandler> messageHandlers;

    @PostConstruct
    public void registerHandlers() {
        if (messageHandlers != null && !messageHandlers.isEmpty()) {
            log.info("开始注册MQTT消息处理器，共 {} 个", messageHandlers.size());
            for (MessageHandler handler : messageHandlers) {
                mqttClient.registerMessageHandler(handler);
            }
            log.info("MQTT消息处理器注册完成");
        } else {
            log.warn("未找到任何MQTT消息处理器");
        }
    }
}
